package com.yowasa.xiuxian.engine.message.battle;

import com.yowasa.xiuxian.annoations.CMD;
import com.yowasa.xiuxian.engine.BattleEngine;
import com.yowasa.xiuxian.entity.bo.battle.BattleContent;
import com.yowasa.xiuxian.engine.message.CmdMessageHandler;
import com.yowasa.xiuxian.entity.bo.user.UserBO;
import com.yowasa.xiuxian.entity.mys.SendMessage;
import com.yowasa.xiuxian.exception.HandlerException;
import com.yowasa.xiuxian.service.helper.BattleHelper;
import com.yowasa.xiuxian.service.helper.MessageHelper;
import com.yowasa.xiuxian.service.helper.UserHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.stream.Collectors;


@CMD(name="/对战")
public class BattleHandler extends CmdMessageHandler {
    @Autowired
    private MessageHelper messageHelper;
    @Autowired
    private UserHelper userHelper;
    @Autowired
    private BattleEngine battleEngine;
    @Autowired
    private BattleHelper battleHelper;



    @Override
    public void execute(SendMessage message) {
        UserBO firstUser = userHelper.checkOpUserAll(message);
        String atUserId = messageHelper.getMysContentAtUserId(message.getContent());
        if (StringUtils.isEmpty(atUserId)) {
            throw new HandlerException("需要at对方与其对战");
        }
        if (firstUser.getUserId().equals(atUserId)) {
            throw new HandlerException("无法和自己对战");
        }
        UserBO secondUser = userHelper.getByUserId(atUserId);
        if (secondUser == null) {
            throw new HandlerException("对方未创建角色 无法对战");
        }
        userHelper.checkCd(secondUser);
        if (!firstUser.getLocal().equals(secondUser.getLocal())){
            throw new HandlerException("对方与你不在同一地点，无法攻击他");
        }
        BattleContent battle = battleEngine.battle(firstUser, secondUser);
        battleHelper.syncUserState(battle);
        int days = battleHelper.calCostTime(battle);
        userHelper.lockUser(battle.getFirst().getUserBO(),days,"正在战斗");
        userHelper.lockUser(battle.getSecond().getUserBO(),days,"正在战斗");
        userHelper.saveUserInfo(battle.getFirst().getUserBO());
        userHelper.saveUserInfo(battle.getSecond().getUserBO());
        String msg = battle.getMsgLog().stream().collect(Collectors.joining("\n"));
        messageHelper.replyMys(message, msg + "\n二人战斗了" + days + "天");
    }

    public String desc(){
        return "艾特别的玩家，与其对战，需要双方在同一地点";
    }

}
